<?php

declare(strict_types=1);

namespace app\api\controller\v1;

use app\admin\BaseXpController;
use app\admin\model\Error;
use app\admin\model\Admin;
use app\admin\model\Token;
use think\facade\Config;
use app\system\model\LogLogin as Log;

class Login extends BaseXpController
{

    /**
     * 错误请求名称
     */
    private $cmd = 'app_login';

    /**
     * 登录接口
     * url: http://域名/api/v1/login
     * doc: http://lutui.net/doc/app/login.html
     */
    public function index()
    {
        $username = input('post.username');
        $password = input('post.password');
        // 1. 检查错误次数
        $check = Error::check($this->cmd);
        if ($check) {
            return json(['error' => '操作过于频繁，请明天再试', 'token' => '']);
        }
        // 2. 检查账户
        $error = '用户或密码错误';
        $token = '';
        $admin = Admin::where('phone', '=', $username)->find();
        if ($admin && password_verify($password, $admin->password)) {
            if ($admin->status != 0) {
                $error = '账号已停用';
            } else {
                $pushToken = input('post.pushToken');
                $device = input('post.device');
                // 3. 生成token
                Token::destroy(function($query) use ($admin){
                    $query->where('platform', 'app')->where('admin_id', $admin->id);
                });
                $error = '';
                $salt = generateSalt();
                $encryptedPassword = crypt($admin->password, Config::get('xp.password_salt') . $admin->salt);
                $auth = $admin->id . "\t" . $encryptedPassword . "\t" . $admin->salt . "\t" . $salt . "\t" . $pushToken . "\t" . $device;
                $token = $this->encrypt($auth);
                Error::clear($this->cmd);
                Error::clear('request');
                // 更新 admin 表
                $obj = new Token();
                $obj->save([
                    'admin_id' => $admin->id,
                    'platform' => 'app',
                    'token' => $token,
                    'salt' => $salt,
                    'push' => $pushToken,
                    'lang' => input('post.lang'),
                    'device' => $device,
                ]);
                Log::add($admin->nickname, '登录成功', 'App', 'Android');
            }
        }
        if ($error) {
            Error::add($this->cmd);
        }
        return json(['error' => $error, 'token' => $token]);
    }
}
